package com.gdkm.database.aop;

import com.gdkm.database.holder.DataSourceContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author HD-0078 杨炜耀
 * @date 2021-5-7 08:55
 */
@Aspect
@Component
@Order(value = 2)
public class DataSourceAspect {

    private static final String[] SLAVE_METHOD = {"query", "select", "get", "list", "find"};

    @Before("execution(* com.gdkm.database.service.*.*(..))")
    public void before(JoinPoint point){
        String methodName = point.getSignature().getName();
        if (isSlave(methodName)) {
            DataSourceContextHolder.markSlave();
        } else {
            DataSourceContextHolder.markMaster();
        }
    }

    @After("execution(* com.gdkm.database.service.*.*(..))")
    public void after(){
        DataSourceContextHolder.clear();
    }

    public boolean isSlave(String methodName){
        return StringUtils.startsWithAny(methodName, SLAVE_METHOD);
    }
}
